﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;

namespace TicketsPhone.Web.Utils
{
    public class Utilidades
    {
        /// <summary>
        /// Funcion encargada de validar si un parametro url no es vacio y es numerico
        /// </summary>
        /// <param name="querystring">valor del parametro a evaluar</param>
        /// <returns></returns>
        public static bool ValidarRequest(string querystring)
        {
            if (string.IsNullOrEmpty(HttpContext.Current.Request.QueryString[querystring]))
            {
                return false;
            }
            else
            {
                int numrequest = 0;
                return int.TryParse(HttpContext.Current.Request.QueryString[querystring], out numrequest);
            }
        }

        /// <summary>
        /// Valida que una variable por querystring venga o no nula
        /// </summary>
        /// <param name="querystring"></param>
        /// <returns></returns>
        public static bool ExisteRequest(string querystring)
        {
            return !string.IsNullOrEmpty(HttpContext.Current.Request.QueryString[querystring]);
        }

        /// <summary>
        /// Agrega una variable al query string, si la variable ya existe, solo le cambia el valor.
        /// </summary>
        /// <param name="variable">nueva variable</param>
        /// <param name="valor">valor de la variable</param>
        public static string AgregarAQueryString(string variable, string valor)
        {
            StringBuilder strQuery = new StringBuilder();
            bool noExiste = true;

            foreach (string llave in HttpContext.Current.Request.QueryString.AllKeys)
            {
                if (strQuery.Length != 0)
                    strQuery.Append("&");

                if (!llave.Equals(variable))
                {
                    strQuery.Append(string.Format("{0}={1}", llave, HttpContext.Current.Request.QueryString[llave]));
                }
                else
                {
                    noExiste = false;
                    strQuery.Append(string.Format("{0}={1}", llave, valor));
                }
            }

            if (noExiste)
            {
                if (strQuery.Length > 0)
                    strQuery.Append("&");

                strQuery.Append(string.Format("{0}={1}", variable, valor));
            }

            return strQuery.ToString();

        }
    }
}